using UnityEngine;
using QFramework;
using System.Linq;
using QAssetBundle;

namespace ProjectSurviver
{
	public partial class SimpleKnife : ViewController
	{
		private float mCurrentScends = 0;

        void Update()
        {
            mCurrentScends += Time.deltaTime;
			if(mCurrentScends >= Global.SimpleAbilityDuretion.Value) // 每15秒执行一次
			{
				mCurrentScends = 0;
				if(Player.Default)
				{
					var enemies = FindObjectsByType<Enemy>(FindObjectsInactive.Exclude, FindObjectsSortMode.None) // 查找所有的敌人
					.OrderBy(enemy=>Player.Default.Distance2D(enemy)).Take(Global.simpleKnifeCount.Value + Global.AdditionFlyThingCount.Value); // 按距离排序，取前5个敌人
					var i = 0;
					foreach (var enemy in enemies)
					{
						if(i < 4) 
						{
							ActionKit.DelayFrame(11 * i, () => // 延迟11帧执行
							{
								AudioKit.PlaySound(Sfx.KNIFE);
								i++;
							}).StartGlobal(); // 启动全局协程
						}

						if(enemy)
						{
							knife.Instantiate()
							.Position(this.Position())
							.Show()
							.Self(self => // 注册一个回调，当飞刀被创建时执行
							{
								var selfCache = self;
								var direction = enemy.NormalizedDirection2DFrom(Player.Default); // 计算飞刀的方向
								self.transform.up = direction; // 设置飞刀的朝向
								var rigidbody2D = self.GetComponent<Rigidbody2D>();
								rigidbody2D.velocity = enemy.NormalizedDirection2DFrom(Player.Default) * 10; // 设置飞刀的速度
								var attackCount = 0;
								self.OnTriggerEnter2DEvent(collider =>
								{
									var hurtBox = collider.GetComponent<HurtBox>();
									if(hurtBox)
									{
										if(hurtBox.Owner.CompareTag("Enemy"))
										{
											var damageTimes = Global.SuperKnife.Value ? Random.Range(2, 3 + 1) : 1; // 计算伤害倍数
											//hurtBox.Owner.GetComponent<Enemy>().Hurt(Global.SimpleKnifeDamage.Value);
											DamageSystem.CalculateDamage(Global.RotateSwordDamage.Value * damageTimes, hurtBox.Owner.GetComponent<Enemy>()); // 计算伤害
											attackCount++;
											if(attackCount >= Global.SimpleKnifeAttackCount.Value) // 如果攻击次数达到上限，销毁飞刀
											{
												selfCache.DestroyGameObjGracefully();
											}
										}
									}
								}).UnRegisterWhenGameObjectDestroyed(self);

								ActionKit.OnUpdate.Register(() =>  //// 注册一个每帧执行的回调
								{
									if(Player.Default)
									{
										// 计算飞刀与玩家的2D距离
										if(Player.Default.Distance2D(selfCache) > 20)
										{
											//// 如果距离超过20单位，销毁飞刀
											self.DestroyGameObjGracefully();
										}
									}
								}).UnRegisterWhenGameObjectDestroyed(self);
							});
						}
					}
				}
			}
        }
    }
}
